package com.sikaryofficial.backend.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sikaryofficial.backend.annotation.TenantFilter;
import com.sikaryofficial.backend.config.ProductQrUrlConfig;
import com.sikaryofficial.backend.constant.EmailConstant;
import com.sikaryofficial.backend.constant.EmailSendSourceEnum;
import com.sikaryofficial.backend.domain.entity.ActivityResult;
import com.sikaryofficial.backend.service.IActivityResultService;
import com.sikaryofficial.backend.service.email.EmailService;
import com.sikaryofficial.common.core.context.SecurityContextHolder;
import com.sikaryofficial.common.core.domain.R;
import com.sikaryofficial.system.api.RemoteUserService;
import com.sikaryofficial.system.api.domain.SysUser;
import com.sikaryofficial.system.api.model.qrcode.ProductQrUrlVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author : qinjinyuan
 * @desc : 活动管理服务
 * @date : 2023/10/30 15:39
 */
@Service
@Slf4j
@RefreshScope
public class ActivityResultManager {
    @Autowired
    private IActivityResultService activityResultService;
    @Resource(name = "asyncTaskExecutor")
    private ThreadPoolTaskExecutor threadPoolExecutor;
    /**
     * 获奖邮件内容
     * {0} 网址 （不同品牌，网址不一样）
     * {1}  单引号
     * {2}  冒号
     * {3}  冒号
     */
    @Value("${hismk.backend.awardsEmailNotice.sendContent}")
    private String sendContent;

    @Value("${hismk.backend.awardsEmailNotice.subject}")
    private String subject;
    @Resource
    private Map<String, EmailService> emailServiceMap;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private ProductQrUrlConfig productQrUrlConfig;

    /**
     * 自动发送邮件通知
     *
     * @return
     */
    @TenantFilter
    public boolean autoSendAwardsEmailNotice() {
        // 需要查询系统有多少 在creatTime > 30分钟未处理，统一进行处理
        log.info("start----awardsEmailNotice-------自动处理");
        List<ActivityResult> reportList = activityResultService.list(new LambdaQueryWrapper<ActivityResult>()
                .eq(ActivityResult::getDeletedVersion, 0L)
                .eq(ActivityResult::getSendMail, 0)
                .last(" limit 10")
        );
        if (CollUtil.isEmpty(reportList)) {
            log.info("end----awardsEmailNotice-------自动处理集合为空");
            return false;
        }
        CompletableFuture[] futures = reportList.stream().map(report -> CompletableFuture.runAsync(() -> autoSendEmailNotice(report), threadPoolExecutor)).toArray(CompletableFuture[]::new);
        CompletableFuture.allOf(futures).join();
        log.info("end-----awardsEmailNotice------自动处理");
        return true;
    }

    /**
     * 发送邮件通知
     * @param activityResult
     */
    private void autoSendEmailNotice(ActivityResult activityResult) {
        // 不区分品牌
        SecurityContextHolder.setBrand("");
        log.info("start--autoSendEmailNotice---getActivityResultId:{}", activityResult.getActivityResultId());
        // 发送邮件及缓存邮箱对象
        String content = MessageFormat.format(sendContent, getBrandUrl(activityResult.getTenantId()), getBrandNo(activityResult.getTenantId()));
        AtomicReference<String> emailAddress = new AtomicReference<>("");
        R<SysUser> result = remoteUserService.getUserByUserId(activityResult.getCreatedBy());
        if (Objects.isNull(result.getData()) || Objects.isNull(result.getData().getEmail())) {
            log.error("remoteUserService.getUserByUserId error");
            return;
        }
        Optional.of(result).ifPresent(user -> emailAddress.set(user.getData().getEmail()));
        if (CharSequenceUtil.isBlank(emailAddress.get())) {
            log.info("start--autoSendEmailNotice---getActivityResultId:未获取到个人邮箱地址");
            return;
        }
        EmailService emailService = emailServiceMap.get(EmailSendSourceEnum.NORMAL.getSendSource() + EmailConstant.SUFFIX);
        emailService.sendHtmlMail(emailAddress.get(), subject, content);
        // 发送完进行数据更新
        activityResultService.updateById(new ActivityResult().setActivityResultId(activityResult.getActivityResultId())
                .setSendMail(1)
                .setUpdatedBy(0L)
                .setUpdatedTime(new Date())
        );
        log.info("end--autoSendEmailNotice---getActivityResultId");
    }

    private String getBrandUrl(Integer tenantId) {
        ProductQrUrlVO productQrUrlVO = productQrUrlConfig.getQrUrlByTenantId(tenantId);
        String brandUrl = productQrUrlVO.getQrUrl();
        if (CharSequenceUtil.isBlank(brandUrl)) {
            return brandUrl;
        }
        return brandUrl.substring(0, brandUrl.indexOf("?"));
    }

    private String getBrandNo(Integer tenantId) {
        ProductQrUrlVO productQrUrlVO = productQrUrlConfig.getQrUrlByTenantId(tenantId);
        String brandNo = productQrUrlVO.getBrandNo();
        if (CharSequenceUtil.isBlank(brandNo)) {
            return "";
        }
        return brandNo;
    }

}
